<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/12 0012
 * Time: 17:55
 */

namespace backend\controllers;


use backend\components\BaseComponentController;
use common\components\ActionsComponents\ListViewAction;
use common\components\DataHelper;
use common\models\Plug\Plug;
use yii\helpers\Url;

class PlugController extends BaseComponentController
{
    public function actions()
    {
        return [
            "index" => [
                "class" => ListViewAction::class,
                "model" => Plug::class,
                "with" => ["mutex" => function($query){
                    $query->select(["id", "name"]);
                }]
            ]
        ]; // TODO: Change the autogenerated stub
    }

    public function actionItem()
    {
        if ( ($id = $this->get("id")) ) {
            $plug = Plug::findOne($id);
            if ( !$plug ) {
                return $this->redirect(Url::to(["index"]));
            }
        } else {
            $plug = [];
        }
        $plugs = Plug::find()->select(["id", "name"]);
        if ( $plug ) {
            $plugs->andWhere("id<>" . $plug->id);
        }
        $plugs = $plugs->orderBy("id desc")->asArray()->all();
        return $this->render("item", [
            "ret" => $plug,
            "plugs" => $plugs
        ]);
    }

    public function actionSet()
    {
        if ( ($id = $this->post("id")) ) {
            $plug = Plug::findOne($id);
            if ( !$plug ) {
                return $this->jsonResponse(self::RESPONSE_FAILURE, "无效的数据");
            }
        } else {
            $plug = new Plug();
            $plug->created_time = DataHelper::date();
            $plug->updated_time = $plug->created_time;
        }
        $plug->attributes = $this->post();
        if ( !$plug->getIsNewRecord() && $plug->id == $plug->mutex_id ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "不能与自己互斥");
        }
        if ( !$plug->save() ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, $plug->getFirstErrorToStr(), $plug->getErrors());
        }
        return $this->jsonResponse(self::RESPONSE_SUCCESS);
    }
}